package com.tiancheng.trade.authserver.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tiancheng.trade.authserver.entity.AuthToken;
import com.tiancheng.trade.authserver.enums.ThirdPlatformEnums;
import com.tiancheng.trade.authserver.enums.TokenTypeEnum;
import com.tiancheng.trade.authserver.mapper.AuthTokenMapper;
import com.tiancheng.trade.commom.web.model.SubjectProfile;
import com.tiancheng.trade.authserver.service.IAuthTokenService;
import com.tiancheng.trade.authserver.utils.TokenGenerator;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * @Author: likailun
 * @Description: 授权角色servie实现
 * @Date: create in 2024/10/21 17:21
 */
@Service
public class AuthTokenServiceImpl extends ServiceImpl<AuthTokenMapper, AuthToken> implements IAuthTokenService {

    @Resource
    private TokenGenerator tokenGenerator;

    @Override
    public String generate(TokenTypeEnum type, long expiresIn, ThirdPlatformEnums thirdPlatform, String thirdClientId, SubjectProfile profile, String thirdToken) {
        AuthToken token = new AuthToken();
        String tokenStr = this.tokenGenerator.generate(expiresIn, profile);
        String tokenMd5 = this.getTokenMD5Digest(tokenStr);

        token.setTokenMd5(tokenMd5);
        token.setMasterId(profile.getId());
        token.setType(type.name());
        token.setToken(tokenStr);
        token.setThirdToken(thirdToken);
        token.setExpire(new Date(System.currentTimeMillis() + (expiresIn * 1000)));
        token.setForceInvalid(false);
        token.setThirdPlatform(thirdPlatform.name());
        token.setThirdClientId(thirdClientId);
        token.setCreatedDt(LocalDateTime.now());
        this.save(token);
        return tokenStr;
    }

    public String getTokenMD5Digest(String token) {
        while (true) {
            try {
                if (token.contains("%")) {
                    token = URLDecoder.decode(token, StandardCharsets.UTF_8);
                    continue;
                }
            } catch (Exception var3) {
            }

            return cn.hutool.crypto.digest.MD5.create().digestHex(token);
        }
    }
}
